package com.jerry.task;

import com.jerry.entity.TaskPo;
import com.jerry.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaskTeceiver {

    private  Logger log = LoggerFactory.getLogger(TaskTeceiver.class);
    private static Map<String, List<String>> taskMap = new HashMap<>();

    /**
     * 记录所有已经提交至此的任务
     * 用于剔除重复的惹怒我
     * 对调用者返回任务个数
     * key   = sysDate 系统当前日期(yyyyMMdd)
     * value = settleDate +"_"+ sysDate 结算日期+系统日期 List
     */
    public synchronized boolean isValidCondition(TaskPo task) {
        log.info("现在的任务个数为："+taskMap.size());

        String dateNow = DateUtils.getTimeNow("yyyyMMdd");
        String yesDay = DateUtils.dealDate(dateNow, -1, "yyyyMMdd");

        List<String> lsTask = null;
        taskMap.remove(yesDay);
        String conditionStr = task.getSettlementDate() +"_"+  task.getSysDate();

        if(taskMap.isEmpty()){
            lsTask = new ArrayList<>();
            taskMap.put(dateNow,lsTask);
        }
        lsTask = taskMap.get(dateNow);
        if(lsTask == null){
            lsTask = new ArrayList<>();
        }else{
            for (String cd: lsTask){
                if(cd.equals(conditionStr)){
                    log.info("reduplicate request .." + conditionStr);
                    return  false;
                }
            }
        }
        lsTask.add(conditionStr);
        taskMap.put(dateNow,lsTask);
        return true;
    }

    /**
     * 获取当前任务数
     * @return
     */
    public int getCurrentTaskCount(){
        List<String> lsTask = null;
        String dateNow = DateUtils.getTimeNow("yyyyMMdd");
        lsTask = taskMap.get(dateNow);
        if(lsTask == null){
            return  0;
        }
        return taskMap.size();
    }
    /**
     * 根据指定的日期进行任务删除
     * @param settleDate
     * @param sysCode
     */
    public  void  clearTaskByDate(String settleDate,String sysCode){
        if(taskMap != null){
            if ("".equals(settleDate) || "".equals(sysCode)) {
                clearTask();
            }else{
                String key = settleDate + "_" + sysCode;
                List<String> lsTask = taskMap.get(0);
                if (lsTask != null) {
                    lsTask.remove(key);
                }
            }
        }

    }
    /**
     * 清空任务
     */
    public  void  clearTask(){
        if(taskMap != null){
            taskMap.clear();
        }
    }
}
